<template>
  <div>
    <ChronicleDetail v-if="showDetail" ref="ChronicleDetail" @closeDetail="closeDetail" @onedit="edit" @delete="handleDelete"></ChronicleDetail>
   
    <a-card v-else>
      <!-- 操作 -->
      <a-row type="flex" justify="end">
        <a-button type="primary" icon="plus" @click="add" v-has="'chronicle:add'">发布</a-button>
      </a-row>

      <!-- 记事列表 -->
      <a-list item-layout="vertical" size="large" :pagination="pagination" :data-source="dataSource">
        <a-list-item slot="renderItem" key="item.title" slot-scope="item">
          <a-avatar
            v-if="item.icon"
            slot="extra"
            shape="square"
            :size="120"
            :src="BaseUrl + item.icon"
            @click="previewImg(BaseUrl + item.icon)"
          />

          <template slot="actions">
            <span @click="edit(item)" v-has="'chronicle:edit'">
              <a-icon type="edit" style="margin-right: 8px" />
            </span>
            <span v-has="'chronicle:delete'">
              <a-popconfirm style="margin-left:10px" title="确定删除?" @confirm="() => handleDelete(item.id)">
                <a-icon type="delete" style="margin-right: 8px" />
              </a-popconfirm>
            </span>
            <span> 发布时间：{{ item.createTime }} </span>
          </template>
          <a-list-item-meta :description="item.description">
            <a slot="title" @click="goDetail(item.id)">{{ item.title }}</a>
          </a-list-item-meta>
          <div v-html="item.simpleContent"></div>
        </a-list-item>
      </a-list>
    </a-card>
 
    <!-- 发布弹窗 -->
    <a-modal destroyOnClose :title="modalTitle" :width="800" v-model="visibleModal" @ok="handleModalOk" @cancel="handleModalCancel">
      <a-form :form="form" style="margin-top: 8px">
        <a-form-item
          label="标题"
          :labelCol="{ span: 5 }"
          :wrapperCol="{ span: 15 }"
        >
          <a-input :maxLength="50" 
          v-decorator="[
            'title',
            {
              initialValue: formData.title,
              rules: [{ required: true, message: '请输入标题！' }]
            }
          ]" placeholder="标题" />
        </a-form-item>
        <a-form-item label="简述" :labelCol="{ span: 5 }" :wrapperCol="{ span: 15 }">
          <a-textarea :maxLength="200" rows="4"
            v-decorator="[
              'simpleContent',
              {
                initialValue: formData.simpleContent,
                rules: [{ required: true, message: '请输入描述！' }]
              }
            ]"
          />
        </a-form-item>

        <a-form-item label="正文" :labelCol="{ span: 5 }" :wrapperCol="{ span: 15 }" style="min-height: 300px">
          <!-- <a-textarea rows="8" v-model="formData.content" /> -->
          <!-- 富文本编辑器 -->
          <j-editor v-model="formData.content" />
        </a-form-item>

        <a-form-item label="封面" :labelCol="{ span: 5 }" :wrapperCol="{ span: 15 }">
          <j-image-upload text="上传图片" v-model="imageList" bizPath="memorabilia" :isMultiple="false"></j-image-upload>     
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 图片预览 -->
    <a-modal :visible="previewVisible" :width="600" :footer="null" @cancel="previewVisible = false">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import ChronicleDetail from './ChronicleDetail'
import JImageUpload from '@/components/jeecg/JImageUpload'
import { filterObj } from '@/utils/util'
import JEditor from '@/components/jeecg/JEditor'
import { getAction, postAction, deleteAction, httpAction } from '@/api/manage'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  components: {
    JImageUpload,
    JEditor,
    ChronicleDetail
  },
  data() {
    return {
      modalTitle: '',
      BaseUrl: window._CONFIG['domianURL'] + '/sys/common/static/',
      url: {
        list: '/memorabilia/list',
        edit: '/memorabilia/edit',
        add: '/memorabilia/add',
        delete: '/memorabilia/delete'
      },
      id: '',
      showDetail:false,
      previewDetail: false,
      queryParam:{
        sortField: 'createTime',
        sortOrder: 'descend'
      },
      dataSource: [],
      pagination: {
        onChange: page => {
          this.pagination.current = page
          this.loadData()
        },
        current:1,
        total:0,
        pageSize: 10
      },
      actions: [
        { type: 'eye', text: 'count' },
        { type: 'edit', text: 'edit' },
        { type: 'delete', text: 'delete' },
        { type: '', text: 'createTime' }
      ],
      actionsMap: {
        edit: 'chronicle:edit',
        delete: 'chronicle:delete'
      },
      visibleModal: false,
      previewVisible: false,
      form: this.$form.createForm(this),
      formData: {},
      imageList: [],
      previewImage: ''
    }
  },
  created(){
    this.id = this.$route.query.id
      if(this.id){
        this.showDetail = true
        this.goDetail(this.id)
      }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    closeDetail(){
      this.id = '';
      this.showDetail = false;
    },
    goDetail(id) {
      this.id = id
      this.showDetail = true;
      this.$nextTick(()=>{
        this.$refs.ChronicleDetail.dataSouce={}
        this.$refs.ChronicleDetail.loadData(id)
      })
    },
    add() {
      this.modalTitle = '新增'
      this.visibleModal = true
    },
    edit(record) {
      this.modalTitle = '编辑'
      this.formData = Object.assign({},record)
      let that = this
      setTimeout(() => {
        that.imageList = record.icon||''
      }, 5)
      this.visibleModal = true
    },
    handleDelete(id) {
      deleteAction(this.url.delete, { id }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    previewImg(url) {
      this.previewImage = url
      this.previewVisible = true
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleModalOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          let httpurl = ''
          let method = ''
          if (!this.formData.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign({},this.formData, {icon:this.imageList.length?this.imageList:''},values)
          httpAction(httpurl, formData, method).then(res => {
            if (res.success) {
              this.formData = {}
              this.imageList = []
              this.form.resetFields();
              this.visibleModal = false
              this.loadData()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
      
      
    },
    handleModalCancel() {
      this.visibleModal = false
      this.formData = {}
      this.imageList = []
      this.form.resetFields();
    },
    loadData() {
      this.id = '';
      this.showDetail = false;
      var params = this.getQueryParams() //查询条件
      this.loading = true
      let self = this
      getAction(this.url.list, params).then(res => {
        if (res.success) {
          self.dataSource = res.result.records
          self.pagination.current = res.result.current
          self.pagination.total = res.result.total
        }
        if (res.code === 510) {
          self.$message.warning(res.message)
        }
        self.loading = false
      })
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.pageNo = this.pagination.current
      param.pageSize = this.pagination.pageSize
      return filterObj(param)
    }
  }
}
</script>

<style scoped>
.col-red {
  color: red;
}
</style>
